<template>
  <div class="main_box">
    <div class="add_wrap">
      <div class="tit">
        <h2>
          ({{ dataInfo.sampleTypeName }}){{ dataInfo.hospitalName }}-{{
            dataInfo.officeName
          }}-> {{ dataInfo.institutionName }}
        </h2>
        <el-button
          plain
          size="small"
          type="success"
          icon="fa fa-mail-forward"
          @click="returnList"
        >
          返 回</el-button
        >
      </div>

      <el-form
        :model="dataForm"
        ref="dataForm"
        :rules="roleRules"
        label-width="120px"
      >
        <el-form-item label="医检条码号" prop="insReportCode">
          <el-input
            v-model="dataForm.insReportCode"
            maxlength="30"
            @change="changeCode"
            show-word-limit
            clearable
            placeholder="请输入号段"
          ></el-input>
          +
          <el-input-number
            v-model="dataForm.endCode"
            :min="0"
            size="large"
            @change="changeCode"
          ></el-input-number>
          <span id="codeLength" style="color: blue;font-size: 18px;"></span>
          <span style="color: red;font-size: 18px;"
            >已录{{ lastCodeSize }}人</span
          >
        </el-form-item>

        <el-form-item label="用户条形码" prop="userCode">
          <el-input
            v-model="dataForm.userCode"
            clearable
            placeholder="请输入条形码"
          ></el-input>
          <el-button
            plain
            type="primary"
            @click="handleClickAddUser"
            size="mini"
            >添加</el-button
          >
        </el-form-item>
        <div style="display: flex;flex-direction: column-reverse;">
          <el-form-item
            prop="userInfoList"
            id="groupUser"
            v-for="(item, index) in dataForm.userInfoList"
            :label="'人员信息-' + (index + 1)"
            :key="'userInfoList' + index"
          >
            <el-input v-model="item.name"></el-input>
            <el-input v-model="item.idCard"></el-input>
            <el-button
              class="deBtn"
              @click="deleteSubclass(index)"
              icon="el-icon-close"
              plain
              type="danger"
              size="mini"
            ></el-button>
          </el-form-item>
        </div>

        <el-form-item style="width: 100%;justify-content: center;">
          <el-button
            style="width: 200px"
            plain
            type="primary"
            v-show="submitBtnShow"
            @click="submitClick"
          >
            提 交
          </el-button>
          <el-button
            style="width: 200px"
            plain
            type="primary"
            v-show="!submitBtnShow"
          >
            提 交 中
          </el-button>
          <!--<el-button @click="returnList">取 消</el-button>-->
        </el-form-item>
      </el-form>

      <el-row class="header-row">
        <el-col>
          <div class="search_wrap">
            <el-form :inline="true" :model="searchForm" ref="searchForm">
              <el-form-item prop="sampleState">
                <el-radio-group
                  v-model="searchForm.sampleState"
                  @change="onSearch"
                >
                  <el-radio :label="0">未录</el-radio>
                  <el-radio :label="1">已录</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="name" style="width: 12%;">
                <el-input
                  style="width: 100%;"
                  v-model="searchForm.name"
                  clearable
                  placeholder="姓名"
                ></el-input>
              </el-form-item>
              <el-form-item prop="idCard" style="width: 15%;">
                <el-input
                  style="width: 100%;"
                  v-model="searchForm.idCard"
                  clearable
                  placeholder="身份证后四位"
                ></el-input>
              </el-form-item>
              <el-form-item
                prop="insReportCode"
                style="width: 20%;"
                v-if="searchForm.sampleState == 1"
              >
                <el-input
                  style="width: 100%;"
                  v-model="searchForm.insReportCode"
                  clearable
                  placeholder="医检条码号"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="small"
                  @click="onSearch(null)"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh-left"
                  size="small"
                  @click="resetForm"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col v-if="searchForm.sampleState == 0">
          <div style="color: red;font-size: 14px;">
            <span>未录人数：{{ tableList.length }}</span>
          </div>
        </el-col>
        <el-col v-if="searchForm.sampleState == 1">
          <div style="color: red;font-size: 14px;">
            <span>已录人数：{{ statisticsInfo.userCount }}</span
            >&nbsp;&nbsp;&nbsp;
            <span>单管个数：{{ statisticsInfo.singleInspection }}</span
            >&nbsp;&nbsp;&nbsp;
            <span>混管个数：{{ statisticsInfo.mixedInspection }}</span>
          </div>
        </el-col>
      </el-row>

      <el-row ref="tableRow" style="width:min-content">
        <el-table
          :data="tableList"
          @row-click="handleClickChoose"
          :fit="true"
        >
          <el-table-column
            prop="applyUserId"
            label="条形码"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="名字"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="idCard"
            label="身份证"
            align="center"
            width="170"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
          prop="payAmount"
          label="付款金额"
          width="100"
          align="center">
          </el-table-column>

          <el-table-column
            prop="insReportCode"
            v-if="searchForm.sampleState == 1"
            label="医检条码号"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="sampleTime"
            v-if="searchForm.sampleState == 1"
            label="采样时间"
            width="95"
            align="center">
          </el-table-column>

          <el-table-column
            prop="createDate"
            label="创建时间"
            width="95"
            align="center">
          </el-table-column>
          <el-table-column
            prop="isChoose"
            label="选中"
            width="100"
            align="center"
            v-if="searchForm.sampleState == 0"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.isChoose" style="color: red;">[已选]</span>
            </template>
          </el-table-column>

          <el-table-column width="100" align="center" label="操作" v-if="searchForm.sampleState == 1">
            <template slot-scope="scope">
              <el-row>
                <el-button @click="reBackApply(scope.row)" size="mini"
                  >撤回</el-button
                >
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页工具条 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNo"
          :page-sizes="[20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, jumper, next, pager, prev"
          :total="page.pageTotal"
        ></el-pagination>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import Region from "@/components/Region";
import SampleApplyApi from "@/api/sample/sampleApply";

export default {
  data() {
    return {
      dataForm: {
        applyId: "",
        endCode: undefined,
        insReportCode: "",
        userCode: "",
        userInfoList: []
      },
      dataInfo: {
        applyId: "",
        itemName: "",
        hospitalId: "",
        institutionId: "",
        institutionName: "",
        hospitalName: "",
        officeName: "",
        address: "",
        applyTime: "",
        remark: "",
        linkMan: "",
        linkPhone: "",
        sampleType: "",
        sampleTypeName: "",
        userInfoList: []
      },
      statisticsInfo: {
        userCount: 0,
        singleInspection: 0,
        mixedInspection: 0
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20
      },
      insReportCodeLength: "34",
      timerRefreshTable: "",
      lastCode: "", // 上一次提交的条码号
      lastCodeSize: 0, // 上一次提交的条码号个数
      loadingIns: false,
      searchForm: {
        applyId: "",
        name: "",
        idCard: "",
        insReportCode: "",
        sampleState: 0
      },
      tableList: [],
      sampleTypeList: [
        { label: "单采", value: 1 },
        { label: "5人混采", value: 5 },
        { label: "10人混采", value: 10 },
        { label: "20人混采", value: 20 }
      ],
      roleRules: {
        insReportCode: [
          { required: true, message: "请输入医检条码号", trigger: "blur" }
        ],
        userInfoList: [
          { required: true, message: "请选择用户", trigger: "change" }
        ]
      },
      //提交按钮显隐
      submitBtnShow: true
    };
  },
  components: {
    Region
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.getData();
      }
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.getData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.getData();
    },
    getData() {
      let _this = this;
      _this.dataForm.applyId = _this.$route.query.id;
      let cond = {
        sampleApplyId: _this.dataForm.applyId,
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize
      };
      SampleApplyApi.getSampleApplyInfo(cond).then(res => {
        _this.$Utils.bindingBean(this.dataInfo, res.data);
        _this.dataInfo.sampleType = parseInt(this.dataInfo.sampleType);
        if (_this.dataInfo.sampleType == 1) {
          _this.dataInfo.sampleTypeName = "单采";
        } else if (this.dataInfo.sampleType == 5) {
          _this.dataInfo.sampleTypeName = "5人混采";
        } else if (_this.dataInfo.sampleType == 10) {
          _this.dataInfo.sampleTypeName = "10人混采";
        } else if (_this.dataInfo.sampleType == 20) {
          _this.dataInfo.sampleTypeName = "20人混采";
        } else {
          _this.dataInfo.sampleTypeName = "采";
        }
        _this.dataForm.applyId = res.data.applyId;
      });

      _this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch(null)
    },
    onSearch(state) {
      let _this = this;
      if (state) {
        _this.searchForm.sampleState = state;
      }
      // 如果是已录，需要查询统计数据
      if (_this.searchForm.sampleState == 1) {
        _this.getStatisticsInfo();
      }
      _this.listTable();
    },
    listTable() {
      let _this = this;
      _this.searchForm.applyId = _this.dataForm.applyId;
      _this.searchForm.pageNo = _this.page.pageNo;
      _this.searchForm.pageSize = _this.page.pageSize;
      SampleApplyApi.getSampleApplyUserByApplyId(_this.searchForm).then(res => {
        _this.tableList = res.data.list;
        _this.page.pageTotal = res.data.total;
        _this.tableList.forEach(item => {
          item.isChoose = false;
          if (
            _this.dataForm.userInfoList &&
            _this.dataForm.userInfoList.length > 0
          ) {
            _this.dataForm.userInfoList.forEach(info => {
              if (info.applyUserId == item.applyUserId) {
                item.isChoose = true;
              }
            });
          }
        });
        // 重新赋值，触发vue动态绑定
        _this.tableList = [].concat(_this.tableList);
      });
    },
    tableRowClassName({ row, rowIndex }) {
      //debugger
      if (row.isChoose == true) {
        return "success-row";
      }
      return "";
    },
    changeCode() {
      let code = this.dataForm.insReportCode;
      if (!this.$Utils.isNull(this.dataForm.endCode)) {
        code = code + this.dataForm.endCode;
      }
      if (code) {
        document.getElementById("codeLength").innerHTML =
          "（" + code.toString().length + "位）";
      }
    },
    getInstitutionId(val) {
      this.dataForm.institutionId = val;
    },
    handleClickChoose(row) {
      let _this = this;
      //debugger
      if (_this.searchForm.sampleState === 1) {
        return;
      }
      if (row.isChoose) {
        return;
      }
      // 判断是否超人数
      if (_this.dataForm.userInfoList.length >= _this.dataInfo.sampleType) {
        _this.$message.error("添加失败，一次提交不能超过限定人数");
        return;
      }
      let addUser = {
        applyUserId: row.applyUserId,
        name: row.name,
        phone: row.phone,
        idCard: row.idCard
      };
      _this.dataForm.userInfoList.push(addUser);
      row.isChoose = true;
      _this.tableList = [].concat(_this.tableList);
    },
    handleClickAddUser() {
      // 调接口获取用户
      let _this = this;
      // 判断当前是否已选中
      if (_this.dataForm.userInfoList.length > 0) {
        let isExists = false;
        _this.dataForm.userInfoList.forEach(item => {
          if (item.applyUserId == _this.dataForm.userCode) {
            isExists = true;
          }
        });
        if (isExists) {
          _this.$message.error("该条码号已录入，请勿重复添加");
          return;
        }
      }

      // 判断是否超人数
      if (_this.dataForm.userInfoList.length >= _this.dataInfo.sampleType) {
        _this.$message.error("添加失败，一次提交不能超过限定人数");
        return;
      }

      let cond = {
        applyUserId: _this.dataForm.userCode,
        applyId: _this.dataForm.applyId
      };
      SampleApplyApi.getSampleApplyUserInfo(cond).then(res => {
        if (res.status == 0 && res.data) {
          if (res.data.sampleState === 1) {
            _this.$message.error("该条码号已录入，请勿重复添加");
            return;
          }
          let userInfo = {
            applyUserId: res.data.applyUserId,
            name: res.data.name,
            phone: res.data.phone,
            idCard: res.data.idCard
          };
          _this.dataForm.userInfoList.push(userInfo);

          // 设置表格对应的人员选中
          _this.tableList.forEach(item => {
            if (item.applyUserId === res.data.applyUserId) {
              item.isChoose = true;
            }
          });
          _this.tableList = [].concat(_this.tableList);
          // 删除表格对应的人员_this.tableList.splice(_this.tableList.findIndex(e => e.applyUserId === res.data.applyUserId), 1)
          _this.dataForm.userCode = "";
        } else {
          _this.$message.error("该条码号不属于当前申请信息");
        }
      });
    },
    // 删除人员
    deleteSubclass(index) {
      let _this = this;
      _this
        .$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {})
        .then(() => {
          let userInfo = _this.dataForm.userInfoList[index];
          // 设置表格对应的人员未选中
          _this.tableList.forEach(item => {
            if (item.applyUserId == userInfo.applyUserId) {
              item.isChoose = false;
            }
          });
          _this.tableList = [].concat(_this.tableList);
          _this.dataForm.userInfoList.splice(index, 1);
        });
    },
    submitClick() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.addApplyCheck();
        }
      });
    },

    addApplyCheck() {
      let _this = this;
      // 一次提交不成超过十个人
      if (
        !_this.dataForm.userInfoList ||
        _this.dataForm.userInfoList.length < 1
      ) {
        _this.$message.error("至少需要选择一人");
        return;
      }
      if (_this.dataForm.userInfoList.length > 20) {
        _this.$message.error("一次提交不能超过20个人");
        return;
      }

      let insReportCode = _this.dataForm.insReportCode.trim();
      if (!_this.$Utils.isNull(_this.dataForm.endCode)) {
        insReportCode = insReportCode + _this.dataForm.endCode;
      }

      // 与上次条码号长度不一致判断
      if (_this.lastCode) {
        if (_this.lastCode.length !== insReportCode.length) {
          this.$confirm(
            message.MSG_CONFIRM_CODE_IS_CHANGE,
            message.TITLE_PROMPT,
            {}
          )
            .then(() => {
              _this.addApply(insReportCode);
            })
            .catch(() => {
              this.$message.info("已取消");
              return;
            });
        } else {
          _this.addApply(insReportCode);
        }
      } else {
        _this.addApply(insReportCode);
      }

      // 判断是否跟当前混采个数相同
      /*if (_this.dataForm.userInfoList.length < _this.dataInfo.sampleType){
        this.$confirm(message.MSG_CONFIRM_NUMBER_IS_NOT_EQUIP, message.TITLE_PROMPT, {})
          .then(() => {

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
            return
          });
      }else{
        // 与上次条码号长度不一致判断
        if (_this.lastCode){
          if (_this.lastCode.length !== insReportCode.length){
            this.$confirm(message.MSG_CONFIRM_CODE_IS_CHANGE, message.TITLE_PROMPT, {})
              .then(() => {
                _this.addApply(insReportCode)
              }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
              return
            });
          }else{
            _this.addApply(insReportCode)
          }
        }else{
          _this.addApply(insReportCode)
        }
      }*/
    },
    addApply(insReportCode) {
      let _this = this;
      _this.submitBtnShow = false;
      let cond = {
        applyId: _this.dataForm.applyId,
        insReportCode: insReportCode,
        userInfoList: _this.dataForm.userInfoList,
        sampleType: this.dataInfo.sampleType
      };
      // console.log(this.dataInfo.sampleType,'采样类型')
      SampleApplyApi.addSampleReport(cond).then(data => {
        if (data.status == 0) {
          _this.$Utils.notifySuccess();
          // 初始化页面
          _this.dataForm.userInfoList = [];
          // 保留医检条码号号段
          _this.lastCode = insReportCode;
          _this.getCountByInsReportCode(insReportCode);
          //_this.lastCodeSize = _this.lastCodeSize + _this.dataForm.userInfoList.length
          /*let insCode = _this.dataForm.insReportCode
            if (insCode && insCode > 6){
              _this.dataForm.insReportCode = insCode.substr(0,6)
            }*/
          _this.getData();
        } else {
          _this.$Utils.notifyError(data.msg);
        }
      });
      _this.submitBtnShow = true;
    },
    getStatisticsInfo() {
      let _this = this;
      let cond = { applyId: _this.dataForm.applyId };
      SampleApplyApi.getStatistics(cond).then(res => {
        if (res.status == 0) {
          _this.$Utils.bindingBean(this.statisticsInfo, res.data);
        }
      });
    },
    getCountByInsReportCode(insReportCode) {
      let _this = this;
      let cond = {
        institutionId: _this.dataInfo.institutionId,
        insReportCode: insReportCode
      };
      SampleApplyApi.getCountByInsReportCode(cond).then(res => {
        if (res.status == 0) {
          _this.lastCodeSize = res.data;
        }
      });
    },
    reBackApply(row) {
      let _this = this;
      let cond = { applyUserId: row.applyUserId };
      SampleApplyApi.reBackSampleReport(cond).then(data => {
        _this.$Utils.notifySuccess();
        // 初始化页面
        _this.listTable();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push("/sample/sampleApplyManagement");
    }
  },
  mounted() {
    this.init();
    if (this.timerRefreshTable) {
      clearInterval(this.timerRefreshTable);
    } else {
      this.timerRefreshTable = setInterval(() => {
        this.listTable();
      }, 5000);
    }
  },
  destroyed() {
    clearInterval(this.timerRefreshTable);
  }
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
.add_wrap {
  height: 87vh;
  padding-top: 10px;
  padding-left: 23px;
}
.main_box {
  padding: 10px;
}
.el-table__body tr.current-row > td {
  background-color: #69a8ea !important;
  color: #fff;
}
/* 2021/8/1 - 19.51 */
.add_wrap .el-form {
  width: 880px;
}
.el-form {
  padding-top: 20px;
}
.el-form .el-input {
  width: 30%;
}
.add_wrap .tit {
  width: 880px;
}
.el-row:nth-child(2) {
  width: 43%;
}
.deBtn {
  border-radius: 15px;
}
.userInfo {
  display: flex;
  flex-direction: row;
  width: 800px;
  justify-content: space-between;
}
#groupUser {
  width: 100%;
}
.el-table__header {
  width: 800px !important;
}
</style>
